package cn.dongqihong.hehe;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletContext;
import java.util.logging.Logger;

/**
 * Created by Dogn on 2017/12/5.
 */
public class JsapiTicketCreater {
    private static Logger logger = Logger.getLogger(JsapiTicketCreater.class.getName());

    public static String getJsapiTicket(ServletContext context) {
        Long ticketExpires = (Long) context.getAttribute("jsapi_ticket_expires");
        String ticket = (String) context.getAttribute("jsapi_ticket");
        Long nowTimestamp = System.currentTimeMillis() / 1000;

        // 过期了
        if (ticketExpires == null || ticket == null || nowTimestamp > ticketExpires) {
            String tokenJson = HttpRequestUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx71d8d8ec094b7897&secret=ae3da1cb48c53fdb5de8a52f428c0f51", "utf-8",false);
            logger.info(tokenJson);
            String token = JSON.parseObject(tokenJson).getString("access_token");
            String ticketJson = HttpRequestUtil.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi", "utf-8",false);
            logger.info(ticketJson);
            ticket = JSON.parseObject(ticketJson).getString("ticket");
            context.setAttribute("jsapi_ticket_expires", nowTimestamp + 7200);
            context.setAttribute("jsapi_ticket", ticket);
        }
        return ticket;
    }

}
